<?php


namespace app\admin\controller;


use app\admin\common\Export;
use app\admin\model\CustomerAppendix;
use app\admin\model\Gather;
use app\admin\model\GatherConfig;
use app\admin\model\GatherType;
use app\admin\model\GatherTypeImage;
use app\admin\model\Item;
use app\admin\model\Page;
use app\BaseController;
use app\Request;
use GuzzleHttp\Client;
use QL\Ext\Baidu;
use QL\QueryList;
use think\facade\View;

class Query extends BaseController
{
    //初始化
    public function initialize()
    {
        parent::initialize();

        $district = Gather::field('district')->distinct(true)->select(); //所属区域
        $businessDistrict = Gather::field('businessDistrict')->distinct(true)->select(); //商圈
        $gather_config = GatherConfig::where(['status' => 1])->select();
        $gather_type = GatherType::select();
        $field_tag = self::CATPATHKEY;
        View::assign('field_tag', $field_tag);
        View::assign('gather_type', $gather_type);
        View::assign('district', $district);
        View::assign('businessDistrict', $businessDistrict);
        View::assign('gather_config', $gather_config);
    }

    /**
     * @param Request $request
     * @return string|\think\response\Json
     * @throws \think\db\exception\DbException
     * 资源显示
     */
    public function index(Request $request)
    {
        if ($request->isAjax()) {
            $where = array();

            if ($request->has('title') && !empty($request->get('title'))) {
                $where[] = array("title", "like", "%" . $request->get('title') . "%");
            }
            if ($request->has('district') && !empty($request->get('district'))) {
                $where[] = array("district", "=", $request->get('district'));
            }

            if ($request->has('businessDistrict') && !empty($request->get('businessDistrict')) && $request->get('businessDistrict') != '无商圈商家') {
                $where[] = array("businessDistrict", "=", $request->get('businessDistrict'));
            }
            //获取每页显示的条数
            $limit = $request->param('limit');
            //获取当前页数
            $page = $request->param('page');
            if ($request->has('businessDistrict') && $request->get('businessDistrict') === '无商圈商家') {
                $result = Gather::where($where)->order('id desc')->whereNull('businessDistrict')->paginate($limit, false, ['page' => $page])->each(function ($item, $key) {
                    $item['createDate'] = date("Y-m-d H:i", $item['createDate']);
                    $item['isChainStore'] = $item['isChainStore'] == 0 ? '连锁' : '个人';
                })->toArray();
            } else {
                $result = Gather::where($where)->order('id desc')->paginate($limit, false, ['page' => $page])->each(function ($item, $key) {
                    $item['createDate'] = date("Y-m-d H:i", $item['createDate']);
                    $item['isChainStore'] = $item['isChainStore'] == 0 ? '连锁' : '个人';
                })->toArray();
            }

            return json(['code' => 200, 'msg' => '', 'total' => $result['total'], 'data' => $result['data']]);
        }

        return View::fetch();
    }

    /**
     * @param Request $request
     * @return string|\think\response\Json
     * @throws \Exception
     * 新增
     */
    public function add(Request $request)
    {
        if ($request->isAjax()) {
            $params = $request->param();
            $badTagDist = $request->param('badTagDist');
            $data = [];
            if (!empty($badTagDist)) {
                $badTagDist = explode(',', $badTagDist);
                foreach ($badTagDist as $key => $value) {
                    $data[] = [
                        'key' => $value,
                        'value' => $value
                    ];
                }
            }
            $externalIds[] = [
                'appCode' => '手动录入',
                'id' => '00000000'
            ];
            $params['badTagDist'] = json_encode($data);
            $params['externalIds'] = json_encode($externalIds);
            if ($params) {
                Gather::create($params);
                return json(['code' => 200, 'url' => '', 'msg' => '添加成功！']);
            }
            return json(['code' => 400, 'url' => '', 'msg' => '新增失败！']);
        }

        return View::fetch();
    }

    //编辑
    public function edit(Request $request, $id)
    {
        $model = Gather::find($id);
        if ($request->isAjax()) {
            $params = $request->param();
            $badTagDist = $request->param('badTagDist');
            $data = [];
            if (!empty($badTagDist)) {
                $badTagDist = explode(',', $badTagDist);
                foreach ($badTagDist as $key => $value) {
                    $data[] = [
                        'key' => $value,
                        'value' => $value
                    ];
                }
            }
            $externalIds[] = [
                'appCode' => '手动录入',
                'id' => '00000000'
            ];

            $params['externalIds'] = json_encode($externalIds);
            $params['badTagDist'] = json_encode($data);
            if ($params) {
                Gather::update($params);
                return json(['code' => 200, 'url' => '', 'msg' => '修改成功！']);
            }
            return json(['code' => 400, 'url' => '', 'msg' => '修改失败！']);
        }
        $badTagDist = $model->badTagDist;
        if (!empty($badTagDist)) {
            $str = "";
            foreach (json_decode($badTagDist) as $k => $v) {
                foreach ($v as $k1 => $v1) {
                    if ($k1 == 'key') {
                        $str .= $v1 . ',';
                    }
                }
            }
            $model->badTagDist = rtrim($str, ',');
        }
        View::assign('model', $model);
        return View::fetch();
    }

    //地图选择坐标
    public function map(Request $request)
    {
        if ($request->isAjax()) {

        }
        return View::fetch();
    }

    //选择上传图片
    public function imageUrl(Request $request, $ids = "", $id = "")
    {

        if ($request->isAjax()) {
            if (!empty($ids)) {
                $ids_arr = explode(',', $ids);
                GatherTypeImage::destroy(array_values($ids_arr));
            }
            $type_id = array_filter($request->param('type_id')); //类别id
            $pic_imgs = array_filter($request->param('pic_imgs')); //文件路径

            $gather_img_ids = "";
            if (!empty($type_id) && !empty($pic_imgs)) {
                foreach ($type_id as $key => $value) {
                    $img_arr = explode(',', $pic_imgs[$key]);
                    $gather_type_image = GatherTypeImage::create([
                        'gather_type_id' => $value,
                        'path' => json_encode($img_arr),
                    ]);
                    $gather_img_ids .= $gather_type_image->id . ',';
                }
                if (!empty($gather_img_ids)) {
                    if (!empty($id)) {
                        $data = [
                            'id' => $id,
                            'image_ids' => rtrim($gather_img_ids, ',')
                        ];
                        Gather::update($data);
                    }
                    return json(['code' => 200, 'data' => rtrim($gather_img_ids, ',')]);
                }
            }
        }
        if (!empty($ids)) {
            $image = GatherTypeImage::whereIn('id', $ids)->select();
            foreach ($image as $key => $value) {
                $value['arr_path'] = json_decode($value['path']);
                $value['string_path'] = implode(',', json_decode($value['path']));
            }
            View::assign('ids', $ids);
            View::assign('id', $id);
            View::assign('image', $image);
            View::assign('count', count($image));
        }
        return View::fetch();
    }

    //文件上传
    public function upload(\think\Request $request)
    {
        $files = $request->file();
        $savename = [];
        foreach ($files as $key => $file) {
            $savename['src'] = \think\facade\Filesystem::disk('public')->putFile('query_file', $file, 'uniqid'); # code...
            $savename['name'] = $file->getOriginalName();
        }
        $data = [
            "code" => 0,
            'msg' => '',
            "data" => $savename,
        ];
        return json($data);
    }

    /**
     * @param Request $request
     * @param string $ids
     * @return \response\Json
     * 删除
     */
    public function del(Request $request, $ids = "")
    {
        if ($request->isAjax() && $ids) {
            $ids = explode(',', $ids);
            $count = Gather::destroy(array_values($ids));
            if ($count) {
                return json(['code' => 200, 'url' => '', 'msg' => '删除成功！']);
            }
        }
    }

    //采集配置
    public function config(Request $request)
    {
        if ($request->isAjax()) {
            $where = array();

            if ($request->has('name') && !empty($request->get('name'))) {
                $where[] = array("name", "like", "%" . $request->get('name') . "%");
            }
            if ($request->has('field_tag') && !empty($request->get('field_tag'))) {
                $where[] = array("field_tag", "=", $request->get('field_tag'));
            }
            //获取每页显示的条数
            $limit = $request->param('limit');
            //获取当前页数
            $page = $request->param('page');
            $result = GatherConfig::where($where)->order('id desc')->paginate($limit, false, ['page' => $page])->each(function ($item, $key) {
                $item['field_tag_name'] = self::CATPATHKEY[$item['field_tag']];
            })->toArray();
            return json(['code' => 200, 'msg' => '', 'total' => $result['total'], 'data' => $result['data']]);
        }
        return View::fetch('query/config/index');
    }

    //导出数据
    public function export(Request $request)
    {
        if ($request->isAjax()) {
            $where = array();
            if (!empty($request->post('ids'))) {
                $where[] = array("id", "in", $request->post('ids'));
            }
            if (!empty($request->post('title'))) {
                $where[] = array("title", "like", "%" . $request->post('title') . "%");
            }
            if (!empty($request->post('district'))) {
                $where[] = array("district", "=", $request->post('district'));
            }
            if (!empty($request->post('businessDistrict'))) {
                $where[] = array("businessDistrict", "=", $request->post('businessDistrict'));
            }
            $xlsName = "选址数据" . time();
            $xlsCell = array(
                array('externalIds', '平台'),
                array('district', '所属区域'),
                array('title', '店铺名称'),
                array('isChainStore', '是否连锁'),
                array('businessDistrict', '商圈名称'),
                array('catPathKey', '分类'),
                array('address', '地址'),
                array('telephones', '电话'),
                array('geoPoint', '经纬度'),
                array('openingHours', '营业时间'),
                array('commentCount', '评论数'),
                array('hasTakeaway', '是否可以外卖'),
                array('likeCount', '点赞数'),
                array('monthSaleCount', '月销量'),
                array('servRating', '服务评分'),
                array('hasBooking', '是否可以预约'),
                array('enviRating', '周边环境评分'),
                array('tags', '标签列表'),
                array('ratingRank', '评分排名，0到1，如0.88表示超过88%的周边商家'),
                array('ratingCount', '评分次数'),
                array('price', '价格'),
                array('avgPrice', '平均价格'),
                array('rating', '评分'),
                array('qualRating', '质量评分'),
                array('minDeliverFee', '最低配送费，单位元'),
                array('deliverFee', '配送费，单位元'),
                array('logiRating', ' 物流评分'),
                array('branchTitle', ' 分店名 '),
                array('goodTagDist', ' 正面标签列表 '),
                array('badTagDist', ' 负面标签列表 '),
            );
            $result = Gather::where($where)->field('externalIds,district,isChainStore,title,businessDistrict,catPathKey,address,telephones,geoPoint,openingHours,commentCount,hasTakeaway,likeCount,monthSaleCount,servRating,hasBooking,enviRating,tags,ratingRank,price,avgPrice,rating,qualRating,minDeliverFee,deliverFee,logiRating,branchTitle,goodTagDist,badTagDist')->select();
            foreach ($result as $key => $value) {
                $externalIds = json_decode($value['externalIds']);
                if (!empty($externalIds)) {
                    $str = "";
                    foreach ($externalIds as $k => $v) {
                        foreach ($v as $k1 => $v1) {
                            if ($k1 == 'appCode') {
                                $str .= $v1 . ',';
                            }
                        }
                    }
                    $value['externalIds'] = rtrim($str, ',');
                }
                $value['isChainStore'] = $value['isChainStore'] == 0 ? '连锁' : '个人';
                $value['hasTakeaway'] = $value['hasTakeaway'] == 1 ? '可以' : '不可以';
                $value['hasBooking'] = $value['hasBooking'] == 0 ? '是' : '否';
                $tag = $value['tags'];
                if (!empty($tag)) {
                    $value['tags'] = implode(',', json_decode($value['tags']));
                }
                $goodTagDist = json_decode($value['goodTagDist']);
                if (!empty($goodTagDist)) {
                    $str = "";
                    foreach (json_decode($value['goodTagDist']) as $k => $v) {
                        foreach ($v as $k1 => $v1) {
                            if ($k1 == 'key') {
                                $str .= $v1 . ',';
                            }
                        }
                    }
                    $value['goodTagDist'] = rtrim($str, ',');
                }
                $badTagDist = json_decode($value['badTagDist']);

                if (!empty($badTagDist)) {
                    $str = "";
                    foreach (json_decode($value['badTagDist']) as $k => $v) {
                        foreach ($v as $k1 => $v1) {
                            if ($k1 == 'key') {
                                $str .= $v1 . ',';
                            }
                        }
                    }
                    $value['badTagDist'] = rtrim($str, ',');
                }
            }
            $export = new Export();
            $url = $export->exportExcel($xlsName, $xlsCell, $result);
            echo json_encode($url);
            exit();


        }
    }

    //读取信息
    public function read($id)
    {
        $model = Gather::find($id);
        $badTagDist = $model->badTagDist;
        if (!empty($badTagDist)) {
            $str = "";
            foreach (json_decode($badTagDist) as $k => $v) {
                foreach ($v as $k1 => $v1) {
                    if ($k1 == 'key') {
                        $str .= $v1 . ',';
                    }
                }
            }
            $model->badTagDist = rtrim($str, ',');
        }
        View::assign('model', $model);
        return View::fetch();
    }

    //海量点
    public function distribution(Request $request)
    {
        if ($request->isAjax()) {
            $where = array();
            if (!empty($request->param('title'))) {
                $where[] = array("title", "like", "%" . $request->param('title') . "%");
            }
            if (!empty($request->param('district'))) {
                $where[] = array("district", "=", $request->param('district'));
            }

            if (!empty($request->param('businessDistrict')) && $request->param('businessDistrict') != '无商圈商家') {
                $where[] = array("businessDistrict", "=", $request->param('businessDistrict'));
            }
            if ($request->param('businessDistrict') === '无商圈商家') {

                $gather = Gather::whereNull('businessDistrict')->field('id,title,geoPoint,district,businessDistrict,address,catPathKey')->where($where)->select();
            } else {
                $gather = Gather::field('id,title,geoPoint,district,businessDistrict,address,catPathKey')->where($where)->select();
            }
            foreach ($gather as $key => $value) {
                if (!is_null($value['geoPoint'])) {
                    $value['point_arr'] = json_decode($value['geoPoint'], true);
                } else {
                    $value['point_arr'] = [
                        'lon' => '',
                        'lat' => ''
                    ];
                }
                $value['catPathKey'] = $value['catPathKey'] ?? '暂无类型';
                $value['businessDistrict'] = $value['businessDistrict'] ?? '暂无匹配';
                $value['district'] = $value['district'] ?? '暂无匹配';
            }

            return json($gather);
        }
        return View::fetch('query/map/index');
    }

    //排名
    public function ranking(Request $request)
    {
        $title = $request->param('title');
        $district = $request->param('district');
        $businessDistrict = $request->param('businessDistrict');
        if ($request->isAjax()) {
            $where = array();
            if ($request->has('title') && !empty($request->param('title'))) {
                $where[] = array("title", "like", "%" . $request->param('title') . "%");
            }
            if ($request->has('district') && !empty($request->param('district'))) {
                $where[] = array("district", "=", $request->param('district'));
            }

            if ($request->has('businessDistrict') && !empty($request->param('businessDistrict')) && $request->param('businessDistrict') != '无商圈商家') {
                $where[] = array("businessDistrict", "=", $request->param('businessDistrict'));
            }
            //获取每页显示的条数
            $limit = $request->param('limit');
            //获取当前页数
            $page = $request->param('page');
            if ($request->has('businessDistrict') && $request->get('businessDistrict') === '无商圈商家') {
                $result = Gather::where($where)->order('rating desc')->whereNull('businessDistrict')->paginate($limit, false, ['page' => $page])->each(function ($item, $key) {
                    $item['createDate'] = date("Y-m-d H:i", $item['createDate']);
                    $item['isChainStore'] = $item['isChainStore'] == 0 ? '连锁' : '个人';
                })->toArray();
            } else {
                $result = Gather::where($where)->order('rating desc')->paginate($limit, false, ['page' => $page])->each(function ($item, $key) {
                    $item['createDate'] = date("Y-m-d H:i", $item['createDate']);
                    $item['isChainStore'] = $item['isChainStore'] == 0 ? '连锁' : '个人';
                })->toArray();
            }

            return json(['code' => 200, 'msg' => '', 'total' => $result['total'], 'data' => $result['data']]);
        }

        return View::fetch('query/ranking', ['title' => $title, 'district' => $district, 'businessDistrict' => $businessDistrict]);
    }

    //同步接口数据
    public function synchronization(Request $request)
    {
        if ($request->isAjax()) {
            $page = $request->param('page');
            $res = Page::max('id', false);
            $zhi = Page::find($res);
            $method = "GET";
            // 请求示例 url 默认请求参数已经做URL编码
            if (!empty($page)) {
                $url = "http://api01.idataapi.cn:8000/restaurant/idataapi?apikey=Pi9bLp6ipC9vQxDJBVZwgXaU4rRez5H3bCOdcti7yqWAqeNGSyCAy1hd3HrPp1pv&city=合肥&pageToken=" . $page;
            } else if (!empty($zhi)) {
                $url = "http://api01.idataapi.cn:8000/restaurant/idataapi?apikey=Pi9bLp6ipC9vQxDJBVZwgXaU4rRez5H3bCOdcti7yqWAqeNGSyCAy1hd3HrPp1pv&city=合肥&pageToken=" . $zhi->pageToken;
            } else {
                $url = "http://api01.idataapi.cn:8000/restaurant/idataapi?apikey=Pi9bLp6ipC9vQxDJBVZwgXaU4rRez5H3bCOdcti7yqWAqeNGSyCAy1hd3HrPp1pv&city=合肥";
            }
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            curl_setopt($ch, CURLOPT_HEADER, FALSE);
            $result = curl_exec($ch);
            $res_decode = json_decode($result, true);
//            Gather::create(['content' => json_encode($res_decode['data'])]);
//            json externalIds openingHours ratingDist imageUrls catName1 telephones otherIds tags addColumn catName2 promotions assistServices badTagDist
            if ($res_decode) {
                foreach ($res_decode['data'] as $key => $value) {
                    $data = [];
                    foreach ($value as $key1 => $value1) {
                        if (is_array($value1)) {
                            $data[$key1] = json_encode($value1);
                        } else {
                            $data[$key1] = $value1;
                        }

                    }
                    unset($data['id'], $data['bulletin']);
                    Gather::create($data);
                }
                //存储新的token
                Page::create([
                    'pageToken' => $res_decode['pageToken']
                ]);
            }
            return json(['code' => 200, 'msg' => '', 'total' => $res_decode['total'], 'pageToken' => $res_decode['pageToken'], 'data' => $res_decode['data']]);
        }
        return View::fetch();
    }
}